package com.mcptt.http.operator.addr;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.cloudptt.api.product.log.Log;
import com.mcptt.comm.CommonFunc;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.config.model.McpttLoginInfo;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.db.model.UserInfo;
import com.mcptt.db.op.AddrDbOperator;
import com.mcptt.http.operator.IHttpAddrOpCb;
import com.mcptt.http.operator.OkHttpUtils;

import android.os.Handler;
import android.os.Message;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AddressLoader implements Callback{
	private static final String HTTP_KEY = "http://";;
	private static final String Sub_Url_Get = ":10010/ias/ue-uas-getusergrpprofile";
	private static final int ConnectionTimeout = 30 * 1000;
	private static final int SoTimeout = 30 * 1000;
	protected final static int OP_SUC = 0;
	protected final static int OP_FAILED = 1;
	private SysConfig config = null;
	private AddrDbOperator dbOperator = null;
	//	private String svrIp = null;
	//	private String num = null;
	//	private String pwd = null;

	protected IHttpAddrOpCb callback = null;

	public AddressLoader(SysConfig config,AddrDbOperator dbOperator,IHttpAddrOpCb callback)
	{
		this.config = config;
		this.dbOperator = dbOperator;
		this.callback = callback;
	}

	public void doGetAddr() {
		new Thread(new Runnable(){
			@Override
			public void run()
			{
				try {
					doGetAddrThread();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void doGetAddrThread() throws Exception
	{
		if(config != null)
		{
			String svrIp = config.getHttpServerInfo().getIp();
			String url = HTTP_KEY + svrIp + Sub_Url_Get;

			McpttLoginInfo mcpttLoginInfo = config.getMcpttLoginInfo();

			McIdInfo userInfo = mcpttLoginInfo.getMcIdInfo();
			String num = userInfo.getUserId();

			Log.debug(getClass(), "doHttpGetThread url = " + url + " num = " + num);
			Map<String, String> params = new HashMap<String, String>();
			params.put("UserID", num);
//			params.put("AccntID", "5555999001");
			OkHttpUtils.getInstance().doPutJson(url, params, this);
		}
	}

	private void sendOpResultMsg(boolean isSuc)
	{
		if(isSuc)
		{
			Message msg = handler.obtainMessage(OP_SUC);
			msg.sendToTarget();
		}
		else
		{
			Message msg = handler.obtainMessage(OP_FAILED);
			msg.sendToTarget();
		}
	}

	protected Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what)
			{
				case OP_SUC:
					if(callback != null)
					{
						callback.onAddrUptResult(true);
					}
					break;
				case OP_FAILED:
					if(callback != null)
					{
						callback.onAddrUptResult(false);
					}
					break;
			}
		}
	};

	@Override
	public void onFailure(Call arg0, IOException arg1) {
		// TODO Auto-generated method stub
		sendOpResultMsg(false);
	}

	@Override
	public void onResponse(Call arg0, Response response) {
		// TODO Auto-generated method stub
		if(response == null)
		{
			sendOpResultMsg(false);
			return;
		}

		Log.debug(getClass(), "onResponse isSuccessful = " + response.isSuccessful());
		if(response.isSuccessful())
		{

			try
			{
				InputStream  instreams = response.body().byteStream();
				String content = CommonFunc.convertStreamToString(instreams);//.convertStreamToString(instreams,"user_not_registered");
				Log.debug(getClass(), "onResponse Content = " + content);

//				JsonParser jsonParser = new JsonParser();
//				JsonObject obj = jsonParser.parse(content).getAsJsonObject();
//				Log.debug(getClass(), "onResponse obj = " + obj);
//				int cause = obj.get("Cause").getAsInt();
//
//				Log.debug(getClass(), "onResponse cause = " + cause);

				if(config != null)
				{
					AddressParser parser = new AddressParser(config);


					boolean isSuc = parser.parse(content);
					if(!isSuc)
					{
						sendOpResultMsg(false);
						return;
					}

					List<GroupInfo> groupList = parser.groupList;
					List<UserInfo> userList = parser.userList;

					dbOperator.deleteAllGroupUser();

					if(parser.groupList != null) {
						Log.debug(getClass(), "onResponse groupList = " + parser.groupList);
						for (Iterator<GroupInfo> itor = groupList.iterator(); itor.hasNext(); ) {
							GroupInfo groupInfo = itor.next();
							Log.debug(getClass(), "onResponse groupInfo = " + groupInfo);
							if(groupInfo != null
								&& groupInfo.getGroupLevel() == 1)
							{
								this.config.setAllCallGNum(groupInfo.getGroupNum());
							}
							if(groupInfo != null
									&& groupInfo.getGroupLevel() == 2)
							{
								this.config.setSosGroupInfo(groupInfo);
							}
							if (groupInfo != null) {
								dbOperator.addGroup(groupInfo);
							}
						}
					}
					doInsertUserInfoToDB(parser.userList);

				}
				else
				{
					sendOpResultMsg(false);
				}

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				sendOpResultMsg(false);
			}
		}
		else
		{
			sendOpResultMsg(false);
			//	    notifyFailed(parserCallback,"readFromSvr code = " + code);
		}
	}

	public void doInsertUserInfoToDB(final List<UserInfo> userList) {
		new Thread(new Runnable(){
			@Override
			public void run()
			{
				try {
					dbOperator.deleteAllUser();
					McIdInfo mcIdInfo = config.getMcInfo();
					if(userList != null) {
						Log.debug(getClass(), "onResponse userList = " + userList);
						for (Iterator<UserInfo> itor = userList.iterator(); itor.hasNext(); ) {
							UserInfo info = itor.next();
							if (info != null) {

								if(info.isSameOne(mcIdInfo))
								{
									config.setMcpttLoginName(info.getName(),info.getMcId());
									info.setOnlineState(1);
								}
								dbOperator.addUser(info);
							}

						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				sendOpResultMsg(true);
			}
		}).start();
	}
}
